package com.zhouixi.service;
import com.zhouixi.entity.Message;
import com.zhouixi.entity.MessageEntity;
import com.zhouixi.repository.MessageRepository;
import jakarta.annotation.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

// 消息存储服务
@Service
public class MessageStorageService {
    @Resource
    private MessageRepository messageRepository;

    public void saveMessage(Message message) {
        MessageEntity entity = new MessageEntity();
        // 拷贝属性（可使用BeanUtils）
        entity.setMsgId(message.getMsgId());
        entity.setSenderId(message.getSenderId());
        entity.setReceiverId(message.getReceiverId());
        entity.setContent(message.getContent());
        entity.setType(message.getType());
        entity.setTimestamp(message.getTimestamp());
        entity.setStatus(message.getStatus());
        messageRepository.save(entity);
    }

    public List<Message> getHistoryMessages(String userId1, String userId2, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        List<MessageEntity> entities = messageRepository
                .findBySenderIdAndReceiverIdOrderByTimestampDesc(userId1, userId2, pageable);
        // 转换为Message对象返回
        return entities.stream().map(this::convertToMessage).collect(Collectors.toList());
    }

    private Message convertToMessage(MessageEntity entity) {
        // 转换逻辑
        return new Message();
    }

    public void updateMessageStatus(String msgId, Integer messageStatus) {

        MessageEntity entity = messageRepository.findByMsgId(msgId);
        if (entity != null) {
            entity.setStatus(messageStatus);
            messageRepository.save(entity);
        }

    }
}